package cn.wolfcode.wms.web.interceptor;

import cn.wolfcode.wms.annotation.RequriedPermission;
import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.util.PermissionUtil;
import cn.wolfcode.wms.util.SecurityByException;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取登录对象,判断是否是超级管理员
        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()) {
            return true;
        }
//        获取请求方法
        HandlerMethod method = (HandlerMethod) handler;
        Method m = method.getMethod();
        RequriedPermission annotation = m.getAnnotation(RequriedPermission.class);
        if (annotation == null){
            return true;
        }
//        从多登陆对象中获取权限
        List<String> expressions = UserContext.getExpression();
//        使用方法获取该方法的权限
        String exp = PermissionUtil.selectexpressionByMethod(m);
        if (expressions.contains(exp)){
            return true;
        }
//        定义个异常方法
//		以前直接跳转路径,现在抛异常
		throw new SecurityByException("权限不足,请及时联系权限管理员");
    }
}
